<?php
namespace app\admin\controller;
use app\admin\model\BeansCommit;
use function foo\func;
use \app\admin\controller\BaseController;
use app\admin\model\OrderBeans;
use app\admin\model\User;
use app\admin\model\UserBank;
use \think\Db;
use think\Validate;
class Beans extends BaseController
{
    protected $order_beans;
    protected $user;
    protected $user_bank;
    public function __construct(OrderBeans $order_beans,User $user,UserBank $user_bank)
    {
       $this->order_beans = $order_beans;
       $this->user = $user;
       $this->user_bank = $user_bank;
    }
	public function index()
	{
        $this->isLogin();
        if(input('search')){
            $result = $this->searchBeansOrder(); //搜索
            if(count($result) == 0){
                return $this->error('您所搜索的订单不存在');
            }
        }else{
            $result = $this->order_beans->order('create_time desc')->paginate(8);
        }
		$list = $this->order_beans->lists();
		return view('beans/index', compact('result','list'));
	}
	/**
	 * 修改订单联豆数量
	 * @param  OrderBeans $order_beans [description]
	 * @return [type]                  [description]
	 */
	public function update()
	{
        $this->isLogin();
		$order_num = input('post.order_num');
		$result = $this->order_beans->where(['order_num' => $order_num])->update(['beans_end_num' => input('post.count')]);
		if(!$result) {
			return $this->error('修改失败');
		}
		return $this->redirect($_SERVER["HTTP_REFERER"]);	}
	/**
	 * 处理订单
	 * @return [type] [description]
	 */
	public function checkoutOrder($order_num, $order_staff, $user_staff)
	{
        $this->isLogin();
		Db::startTrans();
		try{
			$update_order = $this->order_beans->where(['order_num' => $order_num])->update(['order_staff' => $order_staff, 'update_time' => time()]);
			if(!$update_order) {
				throw new \Exception('订单处理失败');
			}
			
			$order = $this->order_beans->where(['order_num' => $order_num])->select();
			$user_beans = $this->user->where(['username' => $order[0]['username']])->select();
			if($user_staff == '1') {
				$user_result = $this->user->where(['username' => $order[0]['username']])->update(['beans' => $user_beans[0]['beans'] - $order[0]['beans_num']]);
			} else {
				$user_result = $this->user->where(['username' => $order[0]['username']])->update(['beans' => $user_beans[0]['beans'] + $order[0]['beans_num']]);
			}
			if(!$user_result) {
				throw new \Exception('用户联豆处理失败');
			}
    		// 提交事务
    		Db::commit();    
		} catch (\Exception $e) {
			return $this->error($e);
    		// 回滚事务
    		Db::rollback();
		}
		return $this->success('成功');
	}
	/**
	 * 订单详情
	 * @param  [type] $order_num [description]
	 * @return [type]            [description]
	 */
	public function beansUpdate($order_num)
	{
        $this->isLogin();
		$result = $this->order_beans->where(['order_num' => $order_num])->select()->toArray();
		if(!$result) {
			return $this->error('订单不存在');
		}
		return view('', compact('result'));
	}
	/**
	 * 订单备注
	 * @param  OrderBeans $order_beans [description]
	 * @return [type]                  [description]
	 */
	public function remarks()
	{
        $this->isLogin();
		if(!input('post.remarks') && !input('post.order_num')) {
			return $this>setError('参数不能为空');
		}
		$post['remarks'] = input('post.remarks');

		$result = $this->order_beans->where(['order_num' => input('post.order_num')])->update($post);
		if(!$result) {
			return $this->setError('添加备注失败');
		}
		return $this->setSuccess('添加备注成功');
	}
	/**
     * 充值订单
     * @param  OrderBeans $order_beans [description]
     * @return [type]            [description]
     */
	public function rechargeOrder()
    {
        $this->isLogin();
        if(input('search')){
            $recharge = $this->searchBeansOrder(); //搜索
            if(count($recharge) == 0){
                return $this->error('您所搜索的订单不存在');
            }
        }else{
            $recharge = $this->order_beans->where('user_staff', 2)->order('create_time')->paginate(5);
        }
        $list = $this->order_beans->lists();
        return view('beans/rechargeOrder',compact('recharge','list'));
    }
    /**
     * 提现订单
     * @param  OrderBeans $order_beans [description]
     * @return [type]            [description]
     */
    public function withdrawOrder()
    {
        $this->isLogin();
        if(input('search')){
            $withdraw = $this->searchBeansOrder(); //搜索
            if(count($withdraw) == 0){
                return $this->error('您所搜索的订单不存在');
            }
        }else{
            $withdraw = $this->order_beans->where('user_staff',1)->order('create_time')->paginate(5);
        }
        $list = $this->order_beans->lists();
        return view('beans/withdrawOrder',compact('withdraw','list'));
    }
    /**
     * 订单搜索
     * @param  OrderBeans $order_beans [description]
     * @return [type]            [description]
     */
    public function searchBeansOrder()
    {
        $this->isLogin();
        $search = input('search');
        if(strlen($search) > 11){
           return $this->order_beans->where('order_num',$search)->paginate(10);
        }else{
            return $this->order_beans->where('username',$search)->paginate(10);
        }
    }
    /**
     * 联豆用户管理之用户列表
     * @param  User $user [description]
     * @return [type]            [description]
     */
    public function beanUser()
    {
        $this->isLogin();
        //用户名或手机号搜索
        if(input('search')){
            $beanUsers=$this->user->with('bankAccount')
                ->where('username',input('search'))
                ->where('user_where',2)
                ->paginate(1);
            if(count($beanUsers) == 0){
                return $this->error('您所搜索的用户不存在');
            }
            $list = count($beanUsers);
        }else{
            //所有联豆用户列表
            $beanUsers = $this->showBankAccount();
            $list = count($beanUsers);
        }
        return view('beans/beanuser',compact('beanUsers','list'));
    }
    /**
     * 联豆用户操作修改联豆数量
     */
     public function beanUserUpdate()
     {
         $this->isLogin();
         $username = input('username');
         $result = $this->user->where('username', $username)->update(['beans' => input('post.count')]);
         if (!$result) {
             return $this->error('修改失败');
         }
         return $this->success('操作成功', 'admin/beans/beanUser');
     }

     /**
      *  联豆用户详情页
      */
     public function beansShow()
     {
        $this->isLogin();
         //1、个人信息
         $userOrders = $this->user->with('orderBeanAccount,bankAccount')
             ->where('user_where',2)
             ->where('username',input('username'))->select();
         //2、用户明细
         $rechargeBeans = $this->order_beans->getRechargeBeans(input('username')); //充值的所有联豆数量
         $rechargeMoney = $this->order_beans->getRechargeMoney(input('username')); //充值总金额
         $withdrawBeans = $this->order_beans->getWithdrawBeans(input('username')); //提现的所有联豆数量
         $withdrawMoney = $this->order_beans->getWithdrawMoney(input('username')); //提现总金额
         //3、所有订单
         $orders = $this->order_beans->where('username',input('username'))->select();
         $rechargeOrders = $this->order_beans->getUserRechargeOrders(input('username'));
         $withdrawOrders = $this->order_beans->getUserWithdrawOrders(input('username'));
         return view('beans/beanuserdesc',compact('userOrders','orders','rechargeBeans','rechargeMoney','withdrawBeans','withdrawMoney','rechargeOrders','withdrawOrders'));
     }
    /**
     * 联豆用户管理详情之充值订单
     * @return \think\response\View
     */
     public function userRechargeOrder()
     {
        $this->isLogin();
         //1、个人信息
         $userOrders = $this->user->with('orderBeanAccount,bankAccount')
             ->where('user_where',2)
             ->where('username',input('username'))->select();
         //2、用户明细
         $rechargeBeans = $this->order_beans->getRechargeBeans(input('username')); //充值的所有联豆数量
         $rechargeMoney = $this->order_beans->getRechargeMoney(input('username')); //充值总金额
         $withdrawBeans = $this->order_beans->getWithdrawBeans(input('username')); //提现的所有联豆数量
         $withdrawMoney = $this->order_beans->getWithdrawMoney(input('username')); //提现总金额
         //3、充值的所有订单
         $orders = $this->order_beans->where('username',input('username'))->select();
         $rechargeOrders = $this->order_beans->getUserRechargeOrders(input('username'));
         $withdrawOrders = $this->order_beans->getUserWithdrawOrders(input('username'));
         return view('beans/userRechargeOrder',compact('userOrders','orders','rechargeBeans','rechargeMoney','withdrawBeans','withdrawMoney','rechargeOrders','withdrawOrders'));
     }
    /**
     * 联豆用户管理详情之提现订单
     * @return \think\response\View
     */
    public function userWithdrawOrder()
    {
        $this->isLogin();
        //1、个人信息
        $userOrders = $this->user->with('orderBeanAccount,bankAccount')
            ->where('user_where',2)
            ->where('username',input('username'))->select();
        //2、用户明细
        $rechargeBeans = $this->order_beans->getRechargeBeans(input('username')); //充值的所有联豆数量
        $rechargeMoney = $this->order_beans->getRechargeMoney(input('username')); //充值总金额
        $withdrawBeans = $this->order_beans->getWithdrawBeans(input('username')); //提现的所有联豆数量
        $withdrawMoney = $this->order_beans->getWithdrawMoney(input('username')); //提现总金额
        //3、提现的所有订单
        $orders = $this->order_beans->where('username',input('username'))->select();
        $rechargeOrders = $this->order_beans->getUserRechargeOrders(input('username'));
        $withdrawOrders = $this->order_beans->getUserWithdrawOrders(input('username'));
//        dump($withdrawOrders);die;
        return view('beans/userWithdrawOrder',compact('userOrders','orders','rechargeBeans','rechargeMoney','withdrawBeans','withdrawMoney','rechargeOrders','withdrawOrders'));
    }
    /**
     * 关联关系获取所有联豆用户
     * @return \think\Paginator
     */
    public function showBankAccount()
    {
        $this->isLogin();
        $user=$this->user->with(['bankAccount'=>function($query){
          //$query->orderTable('create_time desc');
        }])->where('user_where',2)->paginate(10);
       return  $user;
    }
    /**
     * 添加联豆规则
     * @param BeansCommit $beansCommit
     * @return \think\response\View
     */
    public function beanRule(BeansCommit $beansCommit)
    {
        $this->isLogin();
        if(request()->isPost()){
            $data = $_POST;
            $rule = [
                'how_use'  => 'require',
                'how_get'   => 'require',
                'rule' => 'require',
            ];
            $msg = [
                'how_use.require' => '请填写使用规则',
                'how_get.require'     => '请填写获取规则',
                'rule.require'   => '请填写规则',
            ];
            $validate = new Validate($rule, $msg);
            $result   = $validate->check($data);
            if(!$result){
                $this->error( $validate->getError());
            }else{
                $res = $beansCommit->save($data);
                if(!$res){
                    $this->error('规则添加失败');
                }
                $this->success('规则添加成功');
            }
        }
        return view('beans/rules');
    }
}